<template>
    <up-popup :show="show" mode="bottom" round="16" @close="closePicker" :safeAreaInsetBottom="true">
        <view class="date-range-container">
            <!-- 头部操作栏 -->
            <view class="picker-header">
                <text class="btn cancel" @click="handleCancel">取消</text>
                <text class="title">{{ title }}</text>
                <text class="btn confirm" @click="handleConfirm">确定</text>
            </view>

            <!-- 日期选择主体 -->
            <view class="picker-body">
                <!-- 开始日期 -->
                <view class="date-picker">
                    <text class="picker-label">开始日期</text>
                    <picker-view :value="startIndex" @change="handleStartChange" class="picker-view"
						:indicatorStyle="`height: ${ itemHeight }px;`"
						:style="`height: ${ itemHeight * visibleItemCount }px;width: 300rpx;`"
					>
                        <picker-view-column class="picker-view-column">
                            <view class="picker-view-column-view" :style="`height: ${ itemHeight }px;`" v-for="year in years" :key="year" >
								<text class="picker-item" :style="`line-height: ${ itemHeight }px;`">{{ year }}年</text>
							</view>
                        </picker-view-column>
                        <picker-view-column class="picker-view-column" v-if="mode == 'date' || mode == 'yaerMonts'">
                            <view class="picker-view-column-view" :style="`height: ${ itemHeight }px;`" v-for="month in months" :key="month" >
								<text class="picker-item" :style="`line-height: ${ itemHeight }px;`">{{ month }}月</text>
							</view>
                        </picker-view-column>
                        <picker-view-column class="picker-view-column" v-if="mode == 'date'">
                            <view class="picker-view-column-view" :style="`height: ${ itemHeight }px;`" v-for="day in startDays" :key="day" >
								<text class="picker-item" :style="`line-height: ${ itemHeight }px;`">{{ day }}日</text>
							</view>
                        </picker-view-column>
                    </picker-view>
                </view>

                <text class="separator">至</text>

                <!-- 结束日期 -->
                <view class="date-picker">
                    <text class="picker-label">结束日期</text>
                    <picker-view :value="endIndex" @change="handleEndChange" class="picker-view"
						:indicatorStyle="`height: ${ itemHeight }px;`"
						:style="`height: ${ itemHeight * visibleItemCount }px;width: 300rpx;`"
					>
                        <picker-view-column class="picker-view-column">
                            <view class="picker-view-column-view" :style="`height: ${ itemHeight }px;`" v-for="year in years" :key="year">
								<text class="picker-item" :style="`line-height: ${ itemHeight }px;`">{{ year }}年</text>
							</view>
                        </picker-view-column>
                        <picker-view-column class="picker-view-column" v-if="mode == 'date' || mode == 'yaerMonts'">
                            <view class="picker-view-column-view" :style="`height: ${ itemHeight }px;`" v-for="month in months" :key="month">
								<text class="picker-item" :style="`line-height: ${ itemHeight }px;`">{{ month }}月</text>
							</view>
                        </picker-view-column>
                        <picker-view-column class="picker-view-column" v-if="mode == 'date'">
                            <view class="picker-view-column-view" :style="`height: ${ itemHeight }px;`" v-for="day in endDays" :key="day">
								<text class="picker-item" :style="`line-height: ${ itemHeight }px;`">{{ day }}日</text>
							</view>
                        </picker-view-column>
                    </picker-view>
                </view>
            </view>
        </view>
    </up-popup>
</template>

<script>
// 生成范围数组
const range = (start, end) => {
    return Array.from({ length: end - start + 1 }, (_, i) => start + i);
};
/**
 * 年月日范围选择
 */
export default {
    props: {
        show: Boolean,
        defaultValue: {
            type: Array,
            default: () => [new Date(), new Date()]
        },
        // 年份范围 [起始年份, 结束年份]
        yearRange: {
            type: Array,
            default: () => [new Date().getFullYear() - 10, new Date().getFullYear() + 10]
        },
		mode: {
			type: String,
			default: 'date' // yaerMonts  yaer
		},
        title: {
            type: String,
            default: '选择日期范围'
        },
		itemHeight: {
			type: Number,
			default: 44
		},
		visibleItemCount: {
			type: Number,
			default: 6
		}
    },

    data() {
        return {
            years: range(...this.yearRange),
            months: range(1, 12),
            startIndex: [0, 0, 0],
            endIndex: [0, 0, 0]
        };
    },

    computed: {
        // 开始日期天数选项
        startDays() {
            return this.getDays(this.years[this.startIndex[0]], this.months[this.startIndex[1]]);
        },

        // 结束日期天数选项
        endDays() {
            return this.getDays(this.years[this.endIndex[0]], this.months[this.endIndex[1]]);
        },

        // 当前开始日期
        startDate() {
            return this.formatDate(this.startIndex, this.startDays);
        },

        // 当前结束日期
        endDate() {
            return this.formatDate(this.endIndex, this.endDays);
        }
    },

    watch: {
        show(val) {
            if (val) this.$nextTick(this.initDefaultDates);
        }
    },
	mounted() {
		this.$nextTick()
	},
    methods: {
        // 初始化默认日期
        initDefaultDates() {
            const parseDate = (date) => {
                const d = new Date(date);
                return {
                    year: d.getFullYear(),
                    month: d.getMonth() + 1,
                    day: d.getDate()
                };
            };

            const start = parseDate(this.defaultValue[0]);
            const end = parseDate(this.defaultValue[1]);

            this.startIndex = [
				this.years.indexOf(start.year), 
				this.months.indexOf(start.month), 
				this.getDays(start.year, start.month).indexOf(start.day)
			];

            this.endIndex = [
				this.years.indexOf(end.year), 
				this.months.indexOf(end.month), 
				this.getDays(end.year, end.month).indexOf(end.day)
			];
        },

        // 获取当月天数
        getDays(year, month) {
            const date = new Date(year, month, 0);
            return range(1, date.getDate());
        },

        // 处理开始日期变化
        handleStartChange(e) {
            this.startIndex = e.detail.value;
            // 如果结束日期早于开始日期，自动更新结束日期
            if (this.compareDates() < 0) {
                this.endIndex = [...this.startIndex];
            }
        },

        // 处理结束日期变化
        handleEndChange(e) {
            this.endIndex = e.detail.value;
        },

        // 日期比较（返回时间戳差）
        compareDates() {
            const start = new Date(this.years[this.startIndex[0]], this.months[this.startIndex[1]] - 1, this.startDays[this.startIndex[2]]);

            const end = new Date(this.years[this.endIndex[0]], this.months[this.endIndex[1]] - 1, this.endDays[this.endIndex[2]]);

            return end - start;
        },

        // 确认选择
        handleConfirm() {
            if (this.compareDates() < 0) {
                uni.showToast({
                    title: '结束日期不能早于开始日期',
                    icon: 'none'
                });
                return;
            }

            this.$emit('confirm', [this.startDate, this.endDate]);
            this.closePicker();
        },
		handleCancel(){
			this.$emit('cancel');
			this.closePicker();
		},
        // 关闭弹窗
        closePicker() {
            this.$emit('update:show', false);
            this.$emit('close');
        },

        // 格式化日期
        formatDate(indexes, days) {
            const year = this.years[indexes[0]];
            const month = this.months[indexes[1]].toString().padStart(2, '0');
            const day = days[indexes[2]].toString().padStart(2, '0');
			if(this.mode === 'date') {
				return `${year}-${month}-${day}`;
			}else if(this.mode == 'yaerMonts'){
				return `${year}-${month}`;
			}else if(this.mode == 'yaer'){
				return `${year}`;
			}
        }
    }
};
</script>

<style lang="scss" scoped>
.date-range-container {
	display: flex;
	flex-direction: column;
    background: #fff;

    .picker-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 24rpx 32rpx;
        border-bottom: 1rpx solid #eee;

        .title {
            font-size: 34rpx;
            color: #333;
            font-weight: 500;
        }

        .btn {
            padding: 8rpx 24rpx;
            font-size: 30rpx;

            &.cancel {
                color: #999;
            }

            &.confirm {
                color: #2979ff;
            }
        }
    }

    .picker-body {
        display: flex;
        align-items: center;
        padding: 40rpx 20rpx;
        height: 600rpx;

		.date-picker {
			flex: 1;
			display: flex;
			flex-direction: column;
			align-items: center;
		
		    .picker-label {
		        color: #666;
		        font-size: 28rpx;
		        margin-bottom: 15rpx;
		    }
			
			.picker-view {
				position: relative;
				.picker-view-column{
					/* #ifdef APP-NVUE */
					// flex: 1;
					/* #endif */
					display: flex;
					flex-direction: column;
					justify-content: center;
					.picker-view-column-view{
						display: flex;
						align-items: center;
						justify-content: center;
						margin: 0;
						padding: 0;
						.picker-item {
							margin: 0;
							padding: 0;
						    font-size: 28rpx;
						    color: #333;
						}
					}
				}
			}
		}

        .separator {
            margin: 0 32rpx;
            color: #666;
            font-size: 32rpx;
        }
    }
}
</style>
